<template>
  <div class="app-container">
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.number"  clearable />
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="queryParams.username"  clearable />
        </el-form-item>
        <el-form-item label="审批人">
          <el-input v-model="queryParams.appName"  clearable />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select
              v-model="queryParams.status"
              placeholder="单据状态"
              clearable
          >
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核驳回" value="2" />
            <el-option label="待寄回" value="3" />
            <el-option label="已寄回" value="4" />
            <el-option label="处理中" value="5" />
            <el-option label="已完成" value="6" />
            <el-option label="已取消" value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
              v-model="recTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker
              v-model="appTime"
              type="daterange"
              unlink-panels
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              clearable
          />
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>

    </el-row>
    <el-row>
      <el-col>

        <el-button  type="success" :icon="Plus" plain @click="addPage">新增退换货记录</el-button>
        <el-button type="danger" :icon="Delete" plain @click="deleteSelectedRows" :disabled="!isSelectRow">删除</el-button>
        <el-button type="warning" :icon="Upload" plain @click="exportExcel" >导出</el-button>

      </el-col>
    </el-row>
    <el-row >
      <el-table
          :data="userList"
          border
          stripe
          style="height: 545px"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
            prop="msgId"
            label="ID"
            width="80"
        />
        <el-table-column
            prop="msgOrderNo"
            label="退换货单号"
            width="250"
        />
        <el-table-column
            prop="msgType"
            label="退换货类型"
            width="100"
        >
          <template #default="scope">
            <el-text v-if="scope.row.msgType == 1"  type="primary">退货</el-text>
            <el-text v-else-if="scope.row.msgType == 2" type="danger">换货</el-text>
          </template>
        </el-table-column>
        <el-table-column
            width="120"
            prop="msgUsername"
            label="申请人"
        />
        <el-table-column label="申请时间" width="210">
          <template #default="scope">
            {{ formatLoginTime(scope.row.msgCreateTime) }}
          </template>
        </el-table-column>
        <el-table-column
            width="120"
            prop="msgAppName"
            label="审批人"
        />
        <el-table-column label="最后更新时间" width="200">
          <template #default="scope">
            {{ formatLoginTime(scope.row.msgUpdateTime) }}
          </template>
        </el-table-column>
        <el-table-column
            prop="msgStatus"
            label="单据状态"
        >
          <template #default="scope">
            <el-text v-if="scope.row.msgStatus == 0" type="warning">待审核</el-text>
            <el-text v-else-if="scope.row.msgStatus == 1" type="primary">审核通过</el-text>
            <el-text v-else-if="scope.row.msgStatus == 2" type="danger">审核驳回</el-text>
            <el-text v-else-if="scope.row.msgStatus == 3" type="warning">待寄回</el-text>
            <el-text v-else-if="scope.row.msgStatus == 4" type="primary">已寄回</el-text>
            <el-text v-else-if="scope.row.msgStatus == 5" type="primary">处理中</el-text>
            <el-text v-else-if="scope.row.msgStatus == 6" type="success">已完成</el-text>
            <el-text v-else-if="scope.row.msgStatus == 7" type="info">已取消</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" default="scope">
          <template #default="scope">
            <el-button type="primary" size="small" @click="check(scope.row)">查看</el-button>
            <el-button type="primary" size="small" @click="edit(scope.row)">修改</el-button>

            <el-button type="danger" size="small" @click="deleteOne(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-col :span="24">

        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParams.total"
            @size-change="query"
            @current-change="query"
        />
      </el-col>
    </el-row>
  </div>



  <!-- 订单选择弹窗 -->
  <el-dialog v-model="orderSelectVisible" title="选择订单" width="1000px">
    <div class="app-container">
      <el-row>
        <el-form :inline="true" :model="orderSearch" class="demo-form-inline">
          <el-form-item label="订单编号">
            <el-input v-model="orderSearch.ooOrderCode" clearable />
          </el-form-item>
          <el-form-item >
            <el-button type="primary" :icon="Search" @click="queryOrder">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-row >
        <el-table
            :data="orderList"
            border
            stripe
            style="height: 545px"
            @row-click="handleOrderSelect"
        >

          <el-table-column
              prop="ooOrderCode"
              label="订单编号"
              width="170"
          />
          <el-table-column label="下单时间" width="210">
            <template #default="scope">
              {{ formatLoginTime(scope.row.ooOrderTime) }}
            </template>
          </el-table-column>
          <el-table-column
              width="120"
              prop="ooOrderState"
              label="订单状态"
          />
          <el-table-column
              width="120"
              prop="ooCneeName"
              label="收货人"
          />
          <el-table-column
              width="120"
              prop="ooCneeAccount"
              label="会员账号"
          />
          <el-table-column
              width="140"
              prop="ooCneeCellphone"
              label="联系手机"
          />

        </el-table>
      </el-row>

    </div>
    <template #footer>
      <el-button @click="orderSelectVisible = false">取消</el-button>
    </template>
  </el-dialog>












  <!-- 原商品选择弹窗 -->
  <el-dialog v-model="originalGoodsVisible" title="选择原商品" width="940px">
    <div class="app-container">
      <el-row>
        <el-form :inline="true" :model="orderSearch" class="demo-form-inline">
          <el-form-item label="订单编号">
            <el-input v-model="orderSearch.goodsCode" clearable />
          </el-form-item>
          <el-form-item >
            <el-button type="primary" :icon="Search" @click="queryGoods">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-row >
        <el-table
            :data="goodsList"
            border
            stripe
            style="height: 545px"
            @row-click="originalGoodsSelect"
        >

          <el-table-column
              prop="spuNo"
              label="商品编号"
              width="170"
          />
          <el-table-column
              width="180"
              prop="spuName"
              label="商品名称"
          />
          <el-table-column
              width="120"
              prop="spuMoney"
              label="商品单价"
          />
          <el-table-column
              width="120"
              prop="status"
              label="商品状态"
          >
          <template #default="scope">
            <el-text v-if="scope.row.status == 1"  type="warning">在售</el-text>
            <el-text v-else-if="scope.row.status == 2" type="primary">下架</el-text>
            <el-text v-if="scope.row.status == 3"  type="danger">预售</el-text>
          </template>
          </el-table-column>

          <el-table-column
              width="140"
              prop="spuModel"
              label="商品型号"
          />
          <el-table-column
              width="140"
              prop="spuColor"
              label="商品颜色"
          />

        </el-table>
      </el-row>

    </div>
    <template #footer>
      <el-button @click="originalGoodsVisible = false">取消</el-button>
    </template>
  </el-dialog>

  <!-- 退换商品选择弹窗 -->
  <el-dialog v-model="exchangeGoodsVisible" title="选择退换商品" width="800px">
    <el-input v-model="goodsSearch2" placeholder="输入商品编号搜索" style="margin-bottom: 10px"/>
    <el-table :data="goodsList" @row-click="handleExchangeGoodsSelect">
      <el-table-column prop="spuNo" label="商品编号"/>
      <el-table-column prop="spuName" label="商品名称"/>
      <el-table-column prop="spuMoney" label="商品价格"/>
    </el-table>
    <template #footer>
      <el-button @click="exchangeGoodsVisible = false">取消</el-button>
    </template>
  </el-dialog>







  <!-- 添加用户信息 -->
  <el-dialog
      v-model="editFormVisible"
      :title="editTitle"
      width="900px"
      append-to-body
  >
    <!-- 滚动容器：确保滚动条紧邻表单 -->
    <div class="form-scroll-container">
      <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="80px"
      >
        <el-row>
          <el-col>

            <el-button  type="primary" size="small" :icon="Plus" plain @click="selectOrder" :disabled="!isEdit">选择订单及收货人</el-button>
            <el-button type="primary" size="small" :icon="Plus" plain @click="selectOriginalGoods" :disabled="!isEdit">选择原商品</el-button>
            <el-button type="primary" size="small" :icon="Plus" plain @click="selectExchangeGoods" :disabled="!isEdit">选择退换商品</el-button>

          </el-col>
        </el-row>
        <!-- 订单基本资料 -->
        <div class="form-section">
          <h3 class="section-title">订单基本资料</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单编号">
                <el-input v-model="editForm.omOrder.ooOrderCode" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下单日期">
                <el-input v-model="editForm.omOrder.ooOrderTime" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单类型">
                <el-select v-model="editForm.omOrder.ooOrderType" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="普通订单" :value="0" />
                  <el-option label="预售订单" :value="1" />
                  <el-option label="团购订单" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单动作">
                <el-select v-model="editForm.omOrder.ooOrderAction" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="创建订单" :value="0" />
                  <el-option label="支付订单" :value="1" />
                  <el-option label="取消订单" :value="2" />
                  <el-option label="发货" :value="3" />
                  <el-option label="确认收货" :value="4" />
                  <el-option label="申请退款" :value="5" />
                  <el-option label="同意退款" :value="6" />
                  <el-option label="拒绝退款" :value="7" />
                  <el-option label="关闭订单" :value="8" />
                  <el-option label="修改订单" :value="9" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="业务类型">
                <el-select v-model="editForm.omOrder.ooBussinessType" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="电商零售" :value="0" />
                  <el-option label="虚拟货币" :value="1" />
                  <el-option label="生鲜配送" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单状态">
                <el-select v-model="editForm.omOrder.ooOrderState" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="待支付" :value="0" />
                  <el-option label="已支付" :value="1" />
                  <el-option label="待发货" :value="2" />
                  <el-option label="已发货" :value="3" />
                  <el-option label="已完成" :value="4" />
                  <el-option label="已取消" :value="5" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>




        <!-- 收货人资料 -->
        <div class="form-section">
          <h3 class="section-title">收货人资料</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收货人">
                <el-input v-model="editForm.omOrder.ooCneeName" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会员帐号">
                <el-input v-model="editForm.omOrder.ooCneeAccount" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="editForm.omOrder.ooCneePhone" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系手机">
                <el-input v-model="editForm.omOrder.ooCneeCellphone" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮政编码">
                <el-input v-model="editForm.omOrder.ooCneePostalCode" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址">
                <el-input v-model="editForm.omOrder.ooCneeAddress" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配送地区" >
                <el-cascader
                    v-model="selectedRegion"
                    placeholder="请选择省/市"
                    maxlength="30"
                    clearable
                    :options="proCityList"
                    :props="props"
                    @change="onChange"
                    style="width: 330px"
                    :disabled="!isEdit"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配送方式">
                <el-select v-model="editForm.omOrder.ooCneeDeliWay" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="邮政快递" :value="0" />
                  <el-option label="顺丰快递" :value="1" />
                  <el-option label="圆通快递" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="配送费用">
                <el-input v-model="editForm.omOrder.ooCneeDeliFare" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支付方式">
                <el-select v-model="editForm.omOrder.ooCneeDeliMethod" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="微信支付" :value="0" />
                  <el-option label="支付宝" :value="1" />
                  <el-option label="银行卡" :value="2" />
                  <el-option label="货到付款" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电子邮箱">
                <el-input v-model="editForm.omOrder.ooCneeEmail" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input v-model="editForm.omOrder.ooRemark" type="textarea" rows="2" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>



        <!-- 原商品信息 -->
        <div class="form-section">
          <h3 class="section-title">原商品信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品编号">
                <el-input v-model="editForm.tspu.spuNo" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称">
                <el-input v-model="editForm.tspu.spuName" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品型号">
                <el-input v-model="editForm.tspu.spuModel" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品颜色">
                <el-input v-model="editForm.tspu.spuColor" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品价格">
                <el-input v-model="editForm.tspu.spuMoney" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品状态">
                <el-select v-model="editForm.tspu.status" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="在售" :value="1" />
                  <el-option label="下架" :value="2" />
                  <el-option label="预售" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>


        <!-- 退换商品信息 -->
        <div class="form-section">
          <h3 class="section-title">退换商品信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品编号">
                <el-input v-model="editForm.tsSpu.spuNo" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称">
                <el-input v-model="editForm.tsSpu.spuName" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品型号">
                <el-input v-model="editForm.tsSpu.spuModel" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品颜色">
                <el-input v-model="editForm.tsSpu.spuColor" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品价格">
                <el-input v-model="editForm.tsSpu.spuMoney" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品状态">
                <el-select v-model="editForm.tsSpu.status" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="在售" :value="1" />
                  <el-option label="下架" :value="2" />
                  <el-option label="预售" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 退换原因 -->
        <div class="form-section">
          <h3 class="section-title">退换原因</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="退换类型">
                <el-select v-model="editForm.msgType" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="退货" :value="1" />
                  <el-option label="换货" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退换原因">
                <el-select v-model="editForm.msgReasonType" placeholder="请选择" :disabled="!isEdit">
                  <el-option label="质量问题" :value="1" />
                  <el-option label="尺寸不符" :value="2" />
                  <el-option label="七天无理由" :value="3" />
                  <el-option label="其它" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细原因">
                <el-input v-model="editForm.msgReasonDetail" type="textarea" rows="3" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer" v-if="isEdit">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div class="dialog-footer" v-if="!isEdit">
        <el-button @click="cancel">返回</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {
  Clock,
  Delete,
  Edit,
  Search,
  RefreshRight,
  Plus,
  Upload,
  Download
} from '@element-plus/icons-vue'
import {ref,onMounted,computed} from "vue";
import api from '@/utils/request.js';
import {formatDay, formatLoginTime} from '@/utils/date.js'
import {ElMessage, ElMessageBox} from "element-plus";
import loginUser from "@/stores/LoginUser.js";
let recTime = ref(["",""])
let appTime = ref(["",""])
let queryParams =ref({})
let userList = ref([])
let isSelectRow = ref(false)
let isAdd= ref(false);
const tableRef = ref(null);
const selectedRows = ref([]);
let proCityList = ref([])
let selectedRegion = ref([])
let selectedReg = ref([])
// let editForm = ref({})
const isEdit = ref(true);



const editForm = ref({
  // B2cReturnMsg 基础字段
  msgId: '',
  msgOrderNo: '',
  msgOriginalOrderId: '',
  msgUserId: '',
  msgType: '',
  msgReasonType: '',
  msgReasonDetail: '',
  msgStatus: '',
  msgCreateTime: '',
  msgUpdateTime: '',
  msgIsDeleted: '',
  msgAppId: '',
  msgUsername: '',

  // 关联对象
  omOrder: {
    ooId: '',
    ooOrderCode: '',
    ooOrderTime: '',
    ooOrderType: '',
    ooOrderAction: '',
    ooBussinessType: '',
    ooOrderState: '',
    ooCneeName: '',
    ooCneeAccount: '',
    ooCneePhone: '',
    ooCneeCellphone: '',
    ooCneePostalCode: '',
    ooCneeAddress: '',
    ooCneeDeliWay: '',
    ooCneeDeliFare: '',
    ooCneeDeliMethod: '',
    ooCneeEmail: '',
    ooRemark: '',
    ooUpdateTime: '',
    ooPro:'',
    ooCity:'',
  },

  tspu: {
    id: '',
    spuNo: '',
    spuName: '',
    categoryId: '',
    firstCategoryId: '',
    firstCategoryName: '',
    secondCategoryId: '',
    secondCategoryName: '',
    brandId: '',
    unit: '',
    spuMoney: '',
    mainPicUrl: '',
    detailHtml: '',
    status: '',
    sortOrder: '',
    createdTime: '',
    updatedTime: '',
    isDeleted: '',
    brandName: '',
    categoryName: '',
    spuColor:'',
    spuModel:'',
  },

  // 退换货商品信息（用于表单展示）
  tsSpu: {
    spuNo: '',
    spuName: '',
    spuMoney: '',
    status: '',
    spuColor: '',
    spuModel: '',
  },


});


let exportExcel = () => {
  // 拼接查询参数为 URL 编码的键值对
  const queryStr = Object.keys(queryParams.value)
      .map(key => `${key}=${encodeURIComponent(queryParams.value[key])}`)
      .join('&');
  // 构造完整URL并跳转
  window.location.href = `http://127.0.0.1:9090/mag/export/excel?${queryStr}`;
}



let resetQueryForm=()=>{
  queryParams.value = {
    pageNum:1,
    pageSize:10,
    number:'',
    username:'',
    appName:'',
    status:'',
    total:'',
    recStart:'',
    appStart:'',
    recEnd:'',
    appEnd:''
  }
  // 重置级联选择器
  selectedRegion.value = []
}

const props = {
  value: 'repLabel', // 指定选项中作为“值”的字段（如后端返回的地区ID）
  label: 'repVal', // 指定选项中作为“显示文本”的字段（如地区名称）
  children: 'childRep', // 指定选项中作为“子选项列表”的字段（如后端返回的子地区列表字段）
  expandTrigger: 'hover',//鼠标悬浮时显示子数据
};

let queryGoods = () => {
  api.get('/mag/tspu/list',orderSearch.value).then(res=>{
    goodsList.value = res.data
  })
}


let queryOrder = () => {
  api.get('/mag/tspu/list',orderSearch.value).then(res=>{

    orderList.value = res.data

  })
}

let query = ()=>{
  if (recTime.value[0]!==''){
    queryParams.value.recStart = formatDay(recTime.value[0])
    queryParams.value.recEnd = formatDay(recTime.value[1])
  }
  if (appTime.value[0]!==''){
    queryParams.value.appStart = formatDay(appTime.value[0])
    queryParams.value.appEnd = formatDay(appTime.value[1])
  }
  api.get('/mag/query',queryParams.value).then(res=>{
    console.log( res)
    userList.value = res.data.list
    queryParams.value.total = res.data.total
  })

}


// 添加级联选择器变化的处理方法
const onChange = (value) => {
  if (value && value.length) {
    editForm.value.ooPro = value[0]; // 省份值
    editForm.value.ooCity = value[1] || ''; // 城市值，可能不存在
  } else {
    editForm.value.ooPro = '';
    editForm.value.ooCity = '';
  }
};

let switchHandler = (row)=>{
  ElMessageBox.confirm('是否修改用户['+row.id+']的状态？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (row.status == 1){
      row.status = '0'
    }else {
      row.status = '1'
    }
    console.log(row)
    api.post('/repair/save/update',row).then(res=>{
      ElMessage.success('修改成功')
      //query()
    })
  }).catch(() => {
    ElMessage.info('已取消修改');
  })

}
let editFormVisible = ref(false)


let addPage = ()=>{
  // 重置表单数据
  reset();
  // 确保编辑状态为true（可编辑）
  isEdit.value = true;
  // 显示弹窗并设置标题
  editFormVisible.value = true;
  isAdd.value = true;
  editTitle.value = "新增退换货记录";
}




let editFormRules = {

  appealName: [
    { required: true, message: '请输入申诉记录名称', trigger: 'blur' }
  ],
  appealSource: [
    { required: true, message: '请选择申诉来源', trigger: 'change' }
  ],
  appealDesc: [
    { required: true, message: '请输入申诉记录描述', trigger: 'blur' }
  ],
  orderNo: [
    { required: true, message: '请输入订单编号', trigger: 'blur' }
  ],
  orderDate: [
    { required: true, message: '请选择下单日期', trigger: 'change' }
  ],
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入联系手机', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  receiverAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  returnReason: [
    { required: true, message: '请填写退换货原因', trigger: 'blur' }
  ]

}




let check = (row) => {


  // 调用接口获取详情
  api.get('/mag/query/list', { id: row.msgId }).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.msg || '获取详情失败');
      return;
    }

    // 合并数据到 editForm
    editForm.value = {
      ...editForm.value,
      ...res.data,
      omOrder: res.data.omOrder || {},
      tspu: res.data.tspu || {},
      tsSpu: res.data.tsSpu || {}
    };

    // 设置级联选择器
    const order = editForm.value.omOrder;
    if (order.ooPro && order.ooCity) {
      selectedRegion.value = [order.ooPro, order.ooCity];
    } else {
      selectedRegion.value = [];
    }

    // 显示弹窗
    isEdit.value = false;
    editFormVisible.value = true;
    editTitle.value = "退换货申请单";
  }).catch(err => {
    // ElMessage.error('请求失败，请重试');
    console.error(err);
  });
};


let edit = (row)=>{
  // 确保 msgId 存在
  if (!row.msgId) {
    ElMessage.error('数据异常，无法编辑');
    return;
  }

  // 调用接口获取详情（优先使用后端返回的完整数据）
  api.get('/mag/query/list', { id: row.msgId }).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.msg || '获取详情失败');
      return;
    }

    const data = res.data;

    // 合并到 editForm
    editForm.value = {
      ...editForm.value,
      ...data,
      omOrder: data.omOrder || {},
      tspu: data.tspu || {},
      tsSpu: data.tsSpu || {}
    };

    // 设置级联选择器
    const order = editForm.value.omOrder;
    if (order.ooPro && order.ooCity) {
      selectedRegion.value = [order.ooPro, order.ooCity];
    } else {
      selectedRegion.value = [];
    }

    // 显示弹窗
    isEdit.value = true;
    editFormVisible.value = true;
    isAdd.value = false;
    editTitle.value = "退换货申请单";
  }).catch(err => {
    // ElMessage.error('请求失败，请重试');
    console.error(err);
  });
}
/** 取消按钮 */
function cancel() {
  editFormVisible.value = false;
  reset();
}
// 修改 reset 函数，确保所有字段都被正确重置
function reset() {
  // 清空主表单数据
  editForm.value = {
    msgId: '',
    msgOrderNo: '',
    msgOriginalOrderId: '',
    msgUserId: '',
    msgType: '',
    msgReasonType: '',
    msgReasonDetail: '',
    msgStatus: '',
    msgCreateTime: '',
    msgUpdateTime: '',
    msgIsDeleted: '',
    msgAppId: '',
    msgUsername: '',
    omOrder: {
      ooId: '',
      ooOrderCode: '',
      ooOrderTime: '',
      ooOrderType: '',
      ooOrderAction: '',
      ooBussinessType: '',
      ooOrderState: '',
      ooCneeName: '',
      ooCneeAccount: '',
      ooCneePhone: '',
      ooCneeCellphone: '',
      ooCneePostalCode: '',
      ooCneeAddress: '',
      ooCneeDeliWay: '',
      ooCneeDeliFare: '',
      ooCneeDeliMethod: '',
      ooCneeEmail: '',
      ooRemark: '',
      ooUpdateTime: '',
      ooPro: '',
      ooCity: '',
    },
    tspu: {
      id: '',
      spuNo: '',
      spuName: '',
      categoryId: '',
      firstCategoryId: '',
      firstCategoryName: '',
      secondCategoryId: '',
      secondCategoryName: '',
      brandId: '',
      unit: '',
      spuMoney: '',
      mainPicUrl: '',
      detailHtml: '',
      status: '',
      sortOrder: '',
      createdTime: '',
      updatedTime: '',
      isDeleted: '',
      brandName: '',
      categoryName: '',
      spuColor: '',
      spuModel: '',
    },
    tsSpu: {
      spuNo: '',
      spuName: '',
      spuMoney: '',
      status: '',
      spuColor: '',
      spuModel: '',
    },
  };

  // 强制重置级联选择器
  selectedRegion.value = [];
  // 清空搜索相关的响应式变量
  orderSearch.value = {};
  goodsSearch2.value = '';
}


let goodsSearch2 = ref('');


function save() {
   //手动验证级联选择器
  if (!selectedRegion.value || selectedRegion.value.length === 0) {
    ElMessage.error('请选择所在城市')
   return
  }

  // 同步数据到 editForm
  editForm.value.omOrder.ooPro = selectedRegion.value[0] || ''
  editForm.value.omOrder.ooCity = selectedRegion.value[1] || ''

  api.postJson('/mag/save/update',editForm.value).then(res=>{
    console.log(editForm.value)
    if (res.code == 200){
      ElMessage.success("添加/修改成功")
      cancel()
      query()
    }else {
      ElMessage.error(res.msg)
    }

  })
}

const handleSelectionChange = (val) => {
  selectedRows.value = val;
  isSelectRow.value = selectedRows.value.length > 0;
};
const deleteSelectedRows = () => {
  const idsArray = selectedRows.value.map(row => row.msgId);
  ElMessageBox.confirm('是否确认删除用户编号为['+idsArray+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    //ids变成,分割的字符串
    const ids = selectedRows.value.map(row => row.msgId).join(',');
    api.delete('/mag/delete/'+ids).then(res=>{
      ElMessage.success(res.message)
      query()
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
};
let deleteOne = (row)=>{
  ElMessageBox.confirm('是否确认删除用户编号为['+row.msgId+']的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
     api.delete('/mag/delete/'+row.msgId).then(res=>{
      ElMessage.success(res.message)
      query()
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
 }

 function queryRroCityList(){
    api.get('/repair/pro/city').then(res=>{
      proCityList.value = res.data
    })
 }


onMounted(()=>{
  resetQueryForm();
  queryRroCityList();
  query();
})




// 弹窗控制
const orderSelectVisible = ref(false);
const originalGoodsVisible = ref(false);
const exchangeGoodsVisible = ref(false);

// 列表数据
const orderList = ref([]);
const goodsList = ref([]);

// 搜索关键词
const orderSearch = ref({
  ooOrderCode:'',
  goodsCode:'',
  tsGoodsCode:'',
  goodsName:''
});


// 打开订单选择弹窗
const selectOrder = () => {
  orderSelectVisible.value = true;
  // 加载订单列表数据
  api.get('/mag/order/listAll', orderSearch.value).then(res => {
    orderList.value = res.data;

  });
};

// 打开原商品选择弹窗
const selectOriginalGoods = () => {
  originalGoodsVisible.value = true;
  // 加载商品列表数据
  api.get('/mag/tspu/listAll').then(res => {
    goodsList.value = res.data;
  });
};

// 打开退换商品选择弹窗
const selectExchangeGoods = () => {
  exchangeGoodsVisible.value = true;
  // 加载商品列表数据
  api.get('/mag/tspu/listAll').then(res => {
    goodsList.value = res.data;
  });
};

// 选择订单处理
const handleOrderSelect = (row) => {
  editForm.value.omOrder = {
    ...editForm.value.omOrder,
    ooOrderCode: row.ooOrderCode,
    ooOrderTime: row.ooOrderTime,
    ooOrderType: row.ooOrderType,
    ooOrderState: row.ooOrderState,
    ooCneeName: row.ooCneeName,
    ooCneeAccount: row.ooCneeAccount,
    ooCneePhone: row.ooCneePhone,
    ooCneeCellphone: row.ooCneeCellphone,
    ooCneePostalCode: row.ooCneePostalCode,
    ooCneeAddress: row.ooCneeAddress,
    ooCneeDeliWay: row.ooCneeDeliWay,
    ooCneeDeliFare: row.ooCneeDeliFare,
    ooCneeDeliMethod: row.ooCneeDeliMethod,
    ooCneeEmail: row.ooCneeEmail,
    ooRemark: row.ooRemark,
    ooPro: row.ooPro,
    ooCity: row.ooCity,
    ooUpdateTime: row.ooUpdateTime,
    ooOrderAction: row.ooOrderAction,
    ooBussinessType: row.ooBussinessType
  };
  // 设置级联选择器的初始值
  if (row.ooPro && row.ooCity) {
    selectedRegion.value = [row.ooPro, row.ooCity]
  } else {
    selectedRegion.value = []
  }
  orderSelectVisible.value = false;
};

// 选择原商品处理
const originalGoodsSelect = (row) => {
  editForm.value.tspu = {
    ...editForm.value.tspu,
    spuNo: row.spuNo,
    spuName: row.spuName,
    spuModel: row.spuModel,
    spuColor: row.spuColor,
    spuMoney: row.spuMoney,
    spuPicUrl: row.spuPicUrl,
    mainPicUrl: row.mainPicUrl,
    status: row.status,
    sortOrder: row.sortOrder,
    createdTime: row.createdTime,
    updatedTime: row.updatedTime,
    isDeleted: row.isDeleted,
    brandId: row.brandId,
    categoryId: row.categoryId,
    secondCategoryId: row.secondCategoryId,
    brandName: row.brandName,
    categoryName: row.categoryName

  };
  originalGoodsVisible.value = false;
};

// 选择退换商品处理
const handleExchangeGoodsSelect = (row) => {
  editForm.value.tsSpu = {
    ...editForm.value.tsSpu,
    spuNo: row.spuNo,
    spuName: row.spuName,
    spuModel: row.spuModel,
    spuColor: row.spuColor,
    spuMoney: row.spuMoney,
    spuPicUrl: row.spuPicUrl,
    mainPicUrl: row.mainPicUrl,
    status: row.status,
    sortOrder: row.sortOrder,
    createdTime: row.createdTime,
    updatedTime: row.updatedTime,
    brandId: row.brandId,
    categoryId: row.categoryId,
    secondCategoryId: row.secondCategoryId,
    brandName: row.brandName,
    categoryName: row.categoryName
  };
  exchangeGoodsVisible.value = false;
}



</script>



<style scoped>
/* 滚动容器样式 - 确保滚动条紧邻表单 */
.form-scroll-container {
  max-height: 600px; /* 适当增加高度，让内容更舒展 */
  overflow-y: auto;  /* 内容超出时显示滚动条 */
  padding-right: 10px; /* 预留滚动条空间，避免遮挡内容 */
}

/* 区域标题样式 */
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0 10px;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
}

/* 表单项间距优化 */
:deep(.el-form-item) {
  margin-bottom: 12px;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
}
</style>